<?php
namespace control;

// 销售过程统计
class salesProcessStatisticsClass extends adIndexClass
{
	private array $list = [
		'board'      => '数据看板', 'follow_client' => '跟进客户', 'sale_funnel' => '销售漏斗', 'follow_type' => '跟进类型', 'follow_rank' => '跟进排行榜',
		'visit_rank' => '拜访排行榜',
	];
    private const title = '销售过程统计';
	/**
	 * 显示设置
	 *
	 * @return bool|string
	 */
	public function setting()
	{
		$list    = $this->list;
		$li      = '';
		$index   = 0;
		$setting = query('user_setting', "type='销售过程统计' and coid = '".self::$coid."' and stid = '" . self::$stid . "'");
		$setText = (array)json_decode($setting['value'], true);
		foreach ($list as $id => $name) {
			$index++;
			$checked = '';
			if (in_array($id, $setText)) {
				$checked = 'checked';
			}
            $name = L('salesProcessStatistics.list.'.$id);
			$li .= <<<eof
 <li><div class="li-content"><span class="left">{$name}</span><div class="switch">
                  <input id="cmn-toggle-{$index}" name='setting[]' value='{$id}' $checked class="cmn-toggle cmn-toggle-round" type="checkbox">
                  <label for="cmn-toggle-{$index}"></label>
            </div></div></li>
eof;
		}
		$saveWord = L('salesProcessStatistics.setting.save');
		//生成表单
		$html = <<<efo
<form name="settingForm">
<div class="setting-content">
    <ul>
       {$li}
    </ul>
   
</div>
<div style="width: 100%;text-align: center"><button class="button" onclick="subForm('settingForm',root+'control/adIndex.html?cla=salesProcessStatistics&fun=settingEdit')">{$saveWord}</button></div>
</form>
<style>
.li-content{height: 30px;line-height: 30px}
.setting-content>ul{margin: 25px}
.setting-content>ul>li{width: 100%;border-bottom: 1px solid #F2F2F2;padding: 8px 0;}
.switch{display: inline-block;vertical-align: bottom;float: right}
</style>
efo;

		//返回弹出层
		return $this->layer(array("title" => L('salesProcessStatistics.setting.settingChart'), "height" => 440, "width" => 400, "html" => $html));
	}

	/**
	 * 图标展示设置
	 *
	 * @return bool|string
	 */
	public function settingEdit(): bool|string
	{
		$setting = $this->post('setting') ?: [];
		$record  = query('user_setting', "type='销售过程统计' and coid = '".self::$coid."' and stid = '" . self::$stid . "'");
		if (!empty($record['id'])) {
			$json['warn'] = static::update(array(
				'table' => 'user_setting',
				'field' => [
					'value' => json_encode($setting, 320),
				],
				'where' => "id = '$record[id]'",
			));
		} else {
			$json['warn'] = static::insert(array(
				'table' => 'user_setting',
				'field' => [
					'stid'  => self::$stid,
					'type'  => '销售过程统计',
					'value' => json_encode($setting, 320),
				],
			));
		}
		if (in_array($json['warn'], ['新增成功', '更新成功'])) {
			$json['warn'] = 2;
		}
		return json_encode($json, 320);
	}

	/*返回网页*/
	public function home()
	{
		$record        = query('user_setting', "stid = '" . self::$stid . "' and type = '销售过程统计' and coid = '".self::$coid."'");
		$setting       = (array)json_decode($record['value'], true);
		$board         = in_array('board', $setting) ? 'display:block;' : 'display:none;';
		$follow_client = in_array('follow_client', $setting) ? 'display:block;' : 'display:none;';
		$sale_funnel   = in_array('sale_funnel', $setting) ? 'display:block;' : 'display:none;';
		$follow_type   = in_array('follow_type', $setting) ? 'display:block;' : 'display:none;';
		$follow_rank   = in_array('follow_rank', $setting) ? 'display:block;' : 'display:none;';
		$visit_rank    = in_array('visit_rank', $setting) ? 'display:block;' : 'display:none;';
		$root          = root;
		$html          = <<<EOT
<div class="chart_setting"><img onclick="layer('salesProcessStatistics','setting',{})" src="{$root}img/control/menu_two.svg" alt=""></div>
        <div class="home-warp">
          <div class="box-content">
            <div class="data-widget flex-div" style="{$board}">
                {$this->dataBoard(['title' => L('salesProcessStatistics.home.salesData'), 'fun' => 'salesData'])}
            </div>
            <div class="flex-div">
                <div class="flex-div-children data-widget" style="{$sale_funnel}">
                    {$this->dataBoard(['title' => L('salesProcessStatistics.home.cluesData'), 'fun' => 'cluesData'])}
                </div>
                <div class="flex-div-children data-widget" style="{$follow_type}">
                    {$this->dataBoard(['title' => L('salesProcessStatistics.home.followTypeData'), 'fun' => 'followTypeData'])}
                </div>
                <div class="flex-div-children data-widget" style="{$follow_rank}">
                    {$this->top('跟进')}
                </div>
                <div class="data-widget" style="{$visit_rank}">
                    {$this->top('拜访')}
                </div>
            </div>
            <div class= "data-widget flex-div" style="{$follow_client}">
                {$this->dataBoard(['title' => L('salesProcessStatistics.home.followUpData'), 'fun' => 'followUpData'])}
            </div>
          </div>
        </div>
     <script src='{$this->root}static/javascript/echarts.min.js'></script>
EOT;
		$style         = <<<eof
<style>
.data-board-show{height: 200px;}
.home-warp{flex-direction: column}
.m-b-10{margin-bottom: 10px;}
.flex-div{gap: 10px;}
.flex-div>.data-widget:nth-child(2n-1){margin-right: 0;}
</style>
eof;

		return head("ad") . $style . $this->adheader($this->getOnion()) . $html . warn() . $this->adfooter();
	}

	/**
	 * 排行榜
	 */
	public function top(string $type = '跟进'): string
	{
		$endMoon   = date("Y-m");
		$startMoon = date("Y-m", strtotime('-1 month'));
		$fun       = match ($type) {
			'跟进' => 'followData',
			'拜访' => 'visitData'
		};
        $typeWord  = match ($type) {
            '跟进' => L('salesProcessStatistics.top.follow'),
            '拜访' => L('salesProcessStatistics.top.visit'),
        };
//		$text      =
//			"<span class=\"search-ico right\" onclick=\"return searchFormSub('salesProcessStatistics', '{$fun}')\"></span>"
//			. text([
//				"name"    => "month",
//				"title"   => L('salesProcessStatistics.top.timeSlot'),
//				"class"   => "text text-data right contour width200",
//				"value"   => $startMoon . ' ~ ' . $endMoon,
//				'laydate' => ['range' => '~', 'type' => 'month'],
//			]);
        $text = self::searchText([
            'click' => "searchFormSub('salesProcessStatistics', '{$fun}')",
            'search' => true,
            "name" => "month",
            "title" => "时间段",
            "class" => "line28",
            "value" => $startMoon . ' ~ ' . $endMoon,
            'laydate' => ['range' => '~', 'type' => 'month'],
        ]);
		$rankingListWord = L('salesProcessStatistics.top.rankingList');
		$dataQueryWord = L('salesProcessStatistics.top.dataQuery');
        return <<<EOT
        <form name='{$fun}Form' onsubmit="return searchFormSub('salesProcessStatistics', '{$fun}')">
            <div class="frame-title"><span class="title-card">{$typeWord}{$rankingListWord}</span>$text</div>
        </form>
        <div id='{$fun}Html' class='data-box-show top-data-html'>{$dataQueryWord}</div>
        <script>
        $(function(){searchForm('salesProcessStatistics', '{$fun}', 1)});
        </script>
EOT;
	}

	public function followData()
	{
		$date = $this->post('month');
		return $this->topData('跟进', $date);
	}

	public function visitData()
	{
		$date = $this->post('month');
		return $this->topData('拜访', $date);
	}

	public function topData($type, $date)
	{
		$where = '';
		if (!static::isNull($date)) {
			$where .= self::timeComparison($date, 'month', 'time');
		}
		$data = [];
		$sql  = '';
		switch ($type) {
			case '跟进':
				$data = [L('salesProcessStatistics.topData.ranking'), L('salesProcessStatistics.topData.staff'), L('salesProcessStatistics.topData.followTotal'), L('salesProcessStatistics.topData.followClient')];
				$sql  = "SELECT '排名', stid, COUNT(id) AS total , COUNT(IF(target='客户',TRUE,NULL) ) AS khTotal FROM follow WHERE coid='".self::$coid."' {$where} GROUP BY stid ORDER BY total DESC;
                ";
				break;

			case '拜访':
				$data = [L('salesProcessStatistics.topData.ranking'), L('salesProcessStatistics.topData.staff'), L('salesProcessStatistics.topData.visitsNum')];
				$sql  = "SELECT '排名', stid, COUNT(id) AS total FROM visit_plan WHERE coid='".self::$coid."' {$where} GROUP BY stid ORDER BY total DESC;
                ";
				break;
		}
		if (!$sql) {
			return;
		}
		$array = sqlFind($sql);
		array_unshift($array, $data);
		$html = "<ul>\n";
		foreach ($array as $no => $data) {
			$html .= "  <li>";
			foreach ($data as $k => $value) {
				switch ($k) {
					case '排名':
						$value = $no > 0 ? $no : $value;
						break;
					case 'stid':
						$value = self::findStaff($value);
						break;
				}
				$html .= '<span>' . $value . '</span>';
			}
			$html .= "</li>\n";
		}
		$html .= "</ul>";

		return json_encode(['html' => $html], 320);
	}

	/**
	 * 数据看板
	 *
	 * @param array $data 格式 [ 'title'=>'标题', 'fun'=>'数据源函数', 'condition'=> '显示查询条件，为空表示显示' ]
	 */
	public static function dataBoard(array $data)
	{
		$endMoon   = date("Y-m");
		$startMoon = date("Y-m", strtotime('-1 month'));
		$html      = '';
        $staffSelect = self::searchText(array('name' => 'stName', 'id'=>suiji(),'class'=>'width100', 'title' => '员工')) . hidden(array('name' => 'stid', 'value' => ''));

        if (!isset($data['condition']) || $data['condition'] !== false) {
            // 搜索文本框
            $searchTxt = self::searchText([
                'click' => "searchFormSub('" . gets('cla') . "', '{$data['fun']}')",
                'search' => true,
                "name" => "month",
                "title" => "时间段",
                "class" => "line28",
                "value"   => $startMoon . ' ~ ' . $endMoon,
                'laydate' => ['range' => '~', 'type' => 'month',]
            ]);

            $html .= "
                    <form name='{$data['fun']}Form' onsubmit=\"return searchFormSub('" . gets('cla') . "', '{$data['fun']}')\">" .
			         "<div class='frame-title'><span class=\"title-card\">{$data['title']}</span>"
			         . $searchTxt
			         ."<span class='right interval'>".$staffSelect. "</span><input type='submit' value='".L('salesProcessStatistics.topData.search')."' class='text right hide'></div>
                    </form>
                ";
		}
		$html .= "
		<div id='{$data['fun']}Html' class='data-board-show'>".L('salesProcessStatistics.top.dataQuery')."</div>
		<style>
        </style>
		<script>
        $(function(){
            searchForm('" . gets('cla') . "', '{$data['fun']}', 1);
             $('[name=stName]').each(function (){
                  $(this).bigAutocomplete({
                    url:root + 'control/adIndex.html?cla=component&fun=getStaff',
                    callback:function(data,e){
                        e.parent().siblings('input[name=stid]').val(data.id)
                }})  
            })
        });
        </script>";
		//返回
		return $html;
	}

	/**
	 * 总营收
	 *
	 * @return string
	 */
	public function salesData()
	{
		$where = $mwhere = " and coid='".self::$coid."'";
		$stid  = $this->post('stid');
		$date  = $this->post('month');
		if (!static::isNull($stid)) {
			$where  .= " AND stid = '$stid'";
			$mwhere .= " AND manager = '$stid'";
		}
		if (!static::isNull($date)) {
			$where  .= self::timeComparison($date, 'month', 'time');
			$mwhere .= self::timeComparison($date, 'month', 'time');
		}

		$clueTotal = self::formateNumber(static::total([
			'table' => 'clue',
			'where' => $where." and isClient = 0",
		]), '条', true);

		$kehuTotal = self::formateNumber(static::total([
			'table' => 'kehu',
			'where' => $where,
		]), '个', true);

		$opportunityTotal = self::formateNumber(static::total([
			'sql'   => " SELECT ifnull(sum(exSaleMoney), 0) as total FROM `opportunity` ",
			'where' => " `stage` = '已签单' " . $mwhere,
		]), '万', true);

		$contractTotal = self::formateNumber(static::total([
			'sql'   => " SELECT ifnull(sum(money), 0) as total FROM `sales_contract` where 1=1 ",
			'where' => " `state` = '已通过' " . $where,
		]), '万', true);
		$clueTotalWord = L('salesProcessStatistics.salesData.clueTotal');
		$kehuTotalWord = L('salesProcessStatistics.salesData.kehuTotal');
		$opportunityTotalWord = L('salesProcessStatistics.salesData.opportunityTotal');
		$contractTotalWord = L('salesProcessStatistics.salesData.contractTotal');
		$json['html'] = <<<EOT
        <ul class="sales-statistics">
            <li class="left vertical-line">
                <p title="统计所有线索(包含公共线索)的创建时间在搜索时间段内的">{$clueTotalWord}</p>
                <p>{$clueTotal}</p>
            </li>
            <li class="left vertical-line">
                <p title="统计所有客户(包含公客)的创建时间在搜索时间段内的">{$kehuTotalWord}</p>
                <p>{$kehuTotal}</p>
            </li>
            <li class="left vertical-line">
                <p title="统计商机销售阶段为【已签单】的创建时间在搜索时间段内的">{$opportunityTotalWord}</p>
                <p>￥{$opportunityTotal}</p>
            </li>
            <li class="left vertical-line">
                <p title="统计销售合同为【已通过】的创建时间在搜索时间段内的">{$contractTotalWord}</p>
                <p>￥{$contractTotal}</p>
            </li>
        </ul>
EOT;
		return json_encode($json, 320);
	}

	/**
	 * 销售漏斗 - 返回数据
	 *
	 * @return string
	 */
	public function cluesData(): string
	{
		$where = " and coid='".self::$coid."'";
		$stid  = $this->post('stid');
		$date  = $this->post('month');
		if (!static::isNull($stid)) {
			$where .= " AND stid = '$stid'  ";
		}
		if (!static::isNull($date)) {
			$where .= self::timeComparison($date, 'month', 'time');
		}
		$tableArray = ['线索', '潜在客户', '目标客户', '商机', '成交'];
		$result     = [];
		foreach ($tableArray as $type) {
			$total    = match ($type) {
				'线索'   => static::total([
					'table' => 'clue',
					'where' => $where,
				]),
				'潜在客户' => static::total([
					'table' => 'kehu',
					'where' => " `workFlow` in ('初次联系', '跟进客户')" . $where,
				]),
				'目标客户' => static::total([
					'table' => 'kehu',
					'where' => " `workFlow` ='意向客户' " . $where,
				]),
				'商机'   => static::total([
					'table' => 'opportunity',
					'where' => " `stage` = '已签单' " . $where,
				]),
				'成交'   => static::total([
					'table' => 'sales_contract',
					'where' => " `state` ='已通过' " . $where,
				]),
			};
            $typeWord    = match ($type) {
                '线索'   => L('salesProcessStatistics.cluesData.clue'),
                '潜在客户' => L('salesProcessStatistics.cluesData.lead'),
                '目标客户' => L('salesProcessStatistics.cluesData.targetCustomers'),
                '商机'   => L('salesProcessStatistics.cluesData.opportunity'),
                '成交'   => L('salesProcessStatistics.cluesData.deal'),
            };
			$result[] = [
				'name' => $typeWord,
				'data' => $total,
			];
		}
		$data['series'] = $result;
        $data['sort'] ='none';
		$json['html']   = $this->funnel($data);
		return json_encode($json, 320);
	}

	/**
	 * 工资曲线 - 返回数据
	 */
	public function followUpData()
	{
		// 员工查询
		$sWhere = (!static::isNull($this->post('stid'))) ? " stid = '" . $this->post('stid') . "' " : "workFlow='已复核'";
		// 月份查询
		$tWhere = (!static::isNull($this->post('month'))) ? self::timeComparison($this->post('month'), 'mon') : '';
		// 柱状图修饰
		$emphasis    = '{itemStyle: {shadowBlur: 10,shadowColor: \'rgba(0,0,0,0.3)\'}}';
		$barMaxWidth = 45; //柱体最大宽度

		$result = find(['table' => 'staff', 'field' => 'stid, name', 'where' => $sWhere]);
		$name   = $series = [];
		if (is_array($result['array'])) {
			// 遍历数据
			$tableArray = ['跟进线索', '跟进客户', '跟进商机'];
			foreach ($tableArray as $type) {
				$data = match ($type) {
					'跟进线索' => [
                        'table' => 'follow',
						'where' => " AND target = '线索' AND coid = '".self::$coid."'",
					],
					'跟进客户' => [
						'table' => 'follow',
						'where' => " AND target = '客户' AND coid = '".self::$coid."'",
					],
					'跟进商机' => [
						'table' => 'follow',
						'where' => " AND target = '商机' AND coid = '".self::$coid."'",
					],
				};
                $typeWord    = match ($type) {
                    '跟进线索'   => L('salesProcessStatistics.followUpData.followClue'),
                    '跟进客户' => L('salesProcessStatistics.followUpData.followClient'),
                    '跟进商机' => L('salesProcessStatistics.followUpData.followOpportunity'),
                };
				$temp = [];
				// 按照类型遍历员工
				foreach ($result['array'] as $staff) {
					$total = static::total(['table' => $data['table'], 'where' => "stid = '{$staff['stid']}' " . $data['where'] . $tWhere]);
					if($total > 0) {
                        array_push($name, $staff['name']);
                        array_push($temp, $total);
                    }
				}
				$series[] = [
					'name'        => $typeWord,
					'stack'       => 'stack',
					'emphasis'    => $emphasis,
					'barMaxWidth' => $barMaxWidth,
					'data'        => $temp,
				];
			}
		}
		$data         = [
			"name"   => self::filterArray($name),
			"series" => $series,
		];
		$json['html'] = $this->curve($data, 'bar');
		return json_encode($json, 320);
	}

	/**
	 * 跟进类型 - 返回数据
	 *
	 * @return string
	 */
	public function followTypeData(): string
	{
		$where = " AND coid = '".self::$coid."'";
		$stid  = $this->post('stid');
		$date  = $this->post('month');
		if (!static::isNull($stid)) {
			$where .= " AND stid = '$stid' ";
		}
		if (!static::isNull($date)) {
			$where .= self::timeComparison($date, 'month', );
		}
		$sql            = "SELECT `followType` as name, ifnull(COUNT(id), 0) as `data` FROM `follow` WHERE followType <> '' $where GROUP BY followType ORDER BY `data` DESC";
		$data['series'] = sqlFind($sql);;
		$json['html'] = $this->pie($data);
		return json_encode($json, 320);
	}
}
